package com.txf.simple.ui.activity;

import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;
import com.txf.simple.R;
import com.txf.simple.app.AppManager;
import com.txf.simple.ui.view.LoadingCustomView;
import com.txf.simple.utils.UIUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * @author txf
 * @Title 1.activity 基类
 * 2.规划布局分为; 内容层 loading层
 * 3.内容层(子类实现)
 * 3.loading层默认实现 (子类可重写)
 * 4.为6.0以上的版本申请敏感权限 申请权限分为 初始化时申请 运行过程中申请
 * @package com.txf.simple.ui.activity
 * @date 2016/11/21 0021
 */
public abstract class AbsBaseActivity extends AppCompatActivity {
    private View mLoadingView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setBackgroundDrawable(buildWindowBackground());
        AppManager.getInstance().addActivity(this);
        //设置视图到窗口
        setContentView(buildRootLayout());
        initViews();
        //如果初始化申请权限不为空
        if (initAppPermission() != null)
            applicationPermission(new MyPermissionsListener(), initAppPermission());
    }

    /**
     * 设置窗口背景(子类可重写) 默认为透明
     */
    protected Drawable buildWindowBackground() {
        return new ColorDrawable(0x00000000);
    }

    /**
     * 构建根视图
     */
    protected View buildRootLayout() {
        //创建窗口根视图
        FrameLayout rootLayout = new FrameLayout(this);
        //添加主要视图层
        rootLayout.addView(buildMainLayout(), FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
        //构建Loading层
        mLoadingView = buildLoadingView();
        if (mLoadingView != null) {
            hideLoading();
            //添加loading层
            rootLayout.addView(mLoadingView, buildLoadingLayoutParams());
        }
        return rootLayout;
    }

    /**
     * 构建主视图  包含: 标题. 类容. 错误.
     */
    protected View buildMainLayout() {
        //创建主视图
        RelativeLayout rootLayout = new RelativeLayout(this);
        RelativeLayout.LayoutParams titleLP = getRelativeLayoutLayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, UIUtils.dp2px(48));
        RelativeLayout.LayoutParams contentLP = getRelativeLayoutLayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        View errorView = buildErrorView();
//        errorView.setId(R.id.error_layout);
        View contentView = buildContentView();
//        contentView.setId(R.id.content_layout);
        //构建标题
        if (buildTitleView() != null) {
            View title = buildTitleView();
            title.setId(R.id.title_bar);
            //添加标题
            rootLayout.addView(title, titleLP);
            //添加内容层,错误层布局规则
            contentLP.addRule(RelativeLayout.BELOW, R.id.title_bar);
        }
        //添加内容层
        rootLayout.addView(contentView, contentLP);
        //添加错误层
//        rootLayout.addView(errorView, contentLP);
        return rootLayout;
    }
    /**
     * 构建类容视图
     */
    protected abstract View buildContentView();

    /**
     * 初始化View
     */
    protected abstract void initViews();


    /**
     * 构建TitleBar(子类可重写)
     */
    protected View buildTitleView() {
        TextView view = new TextView(this);
        view.setText("标题");
        view.setGravity(Gravity.CENTER);
        return view;
    }
    /**
     * 构建错误层(子类可重写)
     */
    protected View buildErrorView() {
        return null;
    }

    /**
     * @param w 布局宽度
     * @param h 布局高度
     * @return 布局参数
     */
    protected RelativeLayout.LayoutParams getRelativeLayoutLayoutParams(int w, int h) {
        return new RelativeLayout.LayoutParams(w, h);
    }

    /**
     * Loading层(子类可重写)
     */
    protected View buildLoadingView() {
        LoadingCustomView pBar = new LoadingCustomView(this);
        return pBar;
    }

    /**
     * Loading布局参数(子类可重写)
     */
    protected FrameLayout.LayoutParams buildLoadingLayoutParams() {
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(UIUtils.dp2px(70), UIUtils.dp2px(70));
        lp.gravity = Gravity.CENTER;
        return lp;
    }

    /**
     * 显示Loading层
     */
    public void showLoading() {
        if (mLoadingView.getVisibility() == View.INVISIBLE)
            mLoadingView.setVisibility(View.VISIBLE);
    }

    /**
     * 隐藏Loading层
     */
    public void hideLoading() {
        if (mLoadingView.getVisibility() == View.VISIBLE)
            mLoadingView.setVisibility(View.INVISIBLE);
    }

    public Context getContext() {
        return this;
    }

    public AbsBaseActivity getAbsBaseActivity() {
        return this;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppManager.getInstance().delActivity(this);
    }

    /**
     * 6.0 以上版本才有效
     * 页面创建时申请权限 (子类可重写)
     *
     * @return
     */
    protected Collection<String> initAppPermission() {
        return null;
    }

    /**
     * 6.0 以上版本才有效
     * 页面创建时申请权限之后 (子类可重写)
     *
     * @param denides 里面装有 1.申请权限被拒绝或被永久拒绝的权限集合 如果没有数据 就表示获得了所有申请的权限
     */
    protected void initAppPermissionSuccess(List<PermissionDeniedResponse> denides) {

    }

    /**
     * 申请权限 6.0以上
     *
     * @param l           权限申请回调
     * @param permissions 需要申请的权限(多个或单个)
     */
    public void applicationPermission(MultiplePermissionsListener l, Collection<String> permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Collection<String> newPermissions = new ArrayList<>();
            for (String permission : permissions) {
                if (!checkPermission(permission)) {
                    newPermissions.add(permission);
                }
            }
            if (newPermissions.size() > 0)
                Dexter.checkPermissions(l, newPermissions);
        }
    }

    public void applicationPermission(MultiplePermissionsListener l, String... permissions) {
        applicationPermission(l, Arrays.asList(permissions));
    }

    private boolean checkPermission(String permission) {
        return ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * (多个或单个)权限请求结果监听
     */
    public class MyPermissionsListener implements MultiplePermissionsListener {
        /**
         * 该方法在onPermissionRationaleShouldBeShown()之后调用
         * 用户授权之后会走这一步
         */
        @Override
        public void onPermissionsChecked(MultiplePermissionsReport report) {
            List<PermissionDeniedResponse> denides = report.getDeniedPermissionResponses();//拒绝
            initAppPermissionSuccess(denides);
        }

        /**
         * 该方法在onPermissionsChecked()之前被调用
         * 只有当用户有一个或多个没有授权的权限才会回调该方法
         * 如果所有申请的权限都已允许(或者被永久拒绝) 就会不会回调该方法
         * 注意: 初次申请权限 不会回调该方法...
         */
        @Override
        public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
            for (PermissionRequest permissionRequest : permissions) {
                //用户有没有永久拒绝下次进入都会重新申请权限
                token.continuePermissionRequest();
            }
        }
    }
}
